package ct.zxd.wxpay;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ct.zxd.utils.HttpsRequest;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Servlet implementation class HandleWXPayServlet
 */
public class HandleWXPayServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	/**
     * appId
     * */
    private static final String appId="wx8ca51e6343efcb94";
 
    /**
     * mch_id
     * */
    private static final String mchId = "1610102993";
 
    /**
     * key
     * */
    private static final String key = "ZHIXINGQIANLIzhiyunhuicui6270220";
       

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		   //得到openid（微信用户唯一的openid）
			String openid = request.getParameter("openid");
			
		   //得到价钱（自定义）
		   String price = request.getParameter("total_fee");
		   int fee = 0;
		   if (null != price) {
			   float p = Float.parseFloat(price);
		       fee = (int) (p * 100);
		   }
		  
		   //得到商品的ID（自定义）
		   String goodsid=request.getParameter("goodsid");
		   //订单标题（自定义）
		   String title = request.getParameter("title");

		   //时间戳
		   String times = System.currentTimeMillis() + "";
		   
		   //订单编号（自定义 这里以时间戳+随机数）
		   Random random = new Random();
		   String did = times+random.nextInt(1000);
		   
		   SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
//		   packageParams.put("appid",MapUtils.getString(configProperties, "appId"));//微信小程序ID
//		   packageParams.put("mch_id", MapUtils.getString(configProperties, "mch_id"));//商户ID
		   
		   packageParams.put("appid", appId);//微信小程序ID
		   packageParams.put("mch_id", mchId);//商户ID
		   packageParams.put("nonce_str", times);//随机字符串（32位以内） 这里使用时间戳
		   packageParams.put("body", title);//支付主体名称 自定义
		   packageParams.put("out_trade_no", did+"-"+goodsid);//编号 自定义以随机数+商品ID
		   packageParams.put("total_fee", PayUtil.getMoney(price));//价格 自定义
		   //packageParams.put("spbill_create_ip", remoteAddr);
		   packageParams.put("notify_url", "https://mall.weikedashi.net/OrderSys/HandleWXPayCallBackServlet");//支付返回地址要外网访问的到， localhost不行，调用下面buy方法。（订单存入数据库）
		   packageParams.put("trade_type", "JSAPI");//这个api有，固定的
		   packageParams.put("openid", openid);//用户的openid 可以要 可以不要
		   //获取sign(第一次签名)
//		   String sign = PayUtil.createSign("UTF-8", packageParams, MapUtils.getString(configProperties, "mah_password"));//最后这个是自己在微信商户设置的32位密钥
		   String sign = PayUtil.createSign("UTF-8", packageParams, key);//最后这个是自己在微信商户设置的32位密钥
			  
		   
		   /*String mapStr = PayUtil.createLinkString(packageParams);
		   String key = MapUtils.getString(configProperties, "mah_password");
		   //MD5生成运算签名
		   String sign = PayUtil.sign(mapStr,key,"utf-8").toUpperCase();*/
		   packageParams.put("sign", sign);
		   System.out.println(sign);
		   //转成XML
		   String requestXML = PayUtil.getRequestXml(packageParams);
		   
//		   System.out.println(requestXML);
		   
		   //得到含有prepay_id的XML
//		   String resXml = HttpUtils.postData("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXML);
		   String resXml = null;
		   try {
			   resXml = HttpsRequest.sendGetRequest("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXML);
			} catch (Exception e) {
				response.getWriter().write("统一下单失败");
				e.printStackTrace();
				
			}
		   
//		   System.out.println("1------------------");
//		   System.out.println(resXml);
		   //解析XML存入Map
		   Map map2 = null;
		   try {
		       map2 = XmlUtil.doXMLParse(resXml);
		   } catch (Exception e) {
		       e.printStackTrace();
		   }
//		   System.out.println("2------------------");
//		   System.out.println(map2);
		   String return_code = (String) map2.get("return_code");
		   //得到prepay_id 进行二次签名
		   SortedMap<Object, Object> packageP = new TreeMap<Object, Object>();
		   try{
		       if(return_code.equals("SUCCESS")){
		           //获取数据
		           //List<PayInfo> payInfoList =  payService.selectPayInfoByOpenId(openid);
		           //如果等于空，说明为第一次支付
		           /*if(CollectionUtils.isEmpty(payInfoList)){
		               PayInfo payInfo = new PayInfo();
		               payInfo.setPayId(did+goodsid);
		               //设置openid
		               payInfo.setOpenId(openid);
		               //设置金额
		               payInfo.setAmount(fee);
		               //设置说明
		               payInfo.setTitle(title);
		               //设置支付状态
		               payInfo.setPayStatus("0");
		               //插入数据
		               int count = payService.insertPayInfo(payInfo);
		               //判断
		               if(count==1){
		                   log.info("新增支付信息成功");
		               }
		           }else{
		               //判断是否为第一条
		               if(payInfoList.size() == 1){
		                   PayInfo payInfo = payInfoList.get(0);
		                   //更新该条的金额
		                   payInfo.setAmount(fee+payInfo.getAmount());
		                   //更新数据
		                   int count = payService.updateByPayInfo(payInfo);
		                   //判断
		                   if (count==1){
		                       log.info("修改支付信息成功");
		                   }
		               }
		           }*/
//		           PayInfo payInfo = new PayInfo();
//		           payInfo.setPayId(did+goodsid);
//		           //设置openid
//		           payInfo.setOpenId(openid);
//		           //设置金额
//		           payInfo.setAmount(fee);
//		           //设置说明
//		           payInfo.setTitle(title);
//		           //设置支付状态
//		           payInfo.setPayStatus("0");
//		           //插入数据
//		           int count = payService.insertPayInfo(payInfo);
//		           //判断
//		           if(count==1){
//		               log.info("新增支付信息成功");
//		           }
		           String prepay_id = (String) map2.get("prepay_id");
		           //packageP = new TreeMap<Object, Object>();
//		           packageP.put("appId", MapUtils.getString(configProperties, "appId"));//！！！注意，这里是appId,上面是appid
		           
		           packageP.put("appId", appId);//！！！注意，这里是appId,上面是appid
		           packageP.put("nonceStr", times);//时间戳
		           packageP.put("package", "prepay_id=" + prepay_id);//必须把package写成 "prepay_id="+prepay_id这种形式
		           packageP.put("signType", "MD5");//paySign加密
		           packageP.put("timeStamp", (System.currentTimeMillis() / 1000) + "");
		           //得到paySign 用于请求微信
		           /*String payStr = PayUtil.createLinkString(packageP);
		           String paySign =  PayUtil.sign(payStr,key,"utf-8").toUpperCase();*/
//		           String paySign = PayUtil.createSign("UTF-8", packageP, MapUtils.getString(configProperties, "mah_password"));
		           
		           String paySign = PayUtil.createSign("UTF-8", packageP, key);
		           packageP.put("paySign", paySign);
		           packageP.put("success", true);
		       }else{
		           packageP.put("success",false);
		       }
		   }catch (Exception e){
		       e.printStackTrace();
		       System.out.println("接口异常");
		   }
		   //将package 返回给小程序
//		   return packageP;
		   
		   List<SortedMap<Object, Object>> listDish = new ArrayList<SortedMap<Object, Object>>();
		   listDish.add(packageP);
		   JSONArray jsonDish = JSONArray.fromObject(listDish);
           JSONObject jb = new JSONObject();    
           jb.put("dish", jsonDish);     
           
		   response.getWriter().write(jb.toString());

		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
